package cn.lyh.gulimall.product.service;

import cn.lyh.gulimall.product.dao.PmsBrandMapper;
import cn.lyh.gulimall.product.entity.PmsBrand;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mysql.cj.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import utils.PageUtils;

import java.util.Map;

/**
 * @author lyh
 * @version 1.0
 * @since 2021/4/6
 */
@Service
public class PmsBrandService extends ServiceImpl<PmsBrandMapper, PmsBrand> {

	@Autowired
	PmsCategoryBrandRelationService categoryBrandRelationService;

	public PageUtils queryPage(Map<String, Object> params) {
		// 获取key
		String key = (String) params.get("key");
		QueryWrapper<PmsBrand> queryWrapper = new QueryWrapper<>();
		if (!StringUtils.isNullOrEmpty(key)) {
			queryWrapper.eq(PmsBrand.COL_BRAND_ID, key).or().like(PmsBrand.COL_NAME, key);
		}
		// 获取分页数据
		long curPage = params.get("page") != null ? Long.parseLong((String) params.get("page")) : 1;
		long limit = params.get("limit") != null ? Long.parseLong((String) params.get("limit")) : 10;
		IPage<PmsBrand> page = this.page(new Page<>(curPage,limit), queryWrapper);
		return new PageUtils(page);
	}


	@Transactional(rollbackFor = Exception.class)
	public void updateDetail(PmsBrand pmsBrand) {
		// 保证冗余字段的数据一致
		this.updateById(pmsBrand);
		if (!StringUtils.isNullOrEmpty(pmsBrand.getName())) {
			// 同步更新其他关联表中的数据
			categoryBrandRelationService.updateBrand(pmsBrand.getBrandId(),pmsBrand.getName());

			//TODO 更新其他关联
		}
	}
}